package com.kitty.listener;

import com.kitty.listener.annotation.EventHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public enum ListenerManager {

    /**
     * 枚举单例
     */
    INSTANCE;

    private Map<String, Method> map = new HashMap<>();


    public void registerEventHandler(Object handler) {
        Method[] methods = handler.getClass().getDeclaredMethods();
        for (Method method : methods) {
            EventHandler mapperAnnotation = method.getAnnotation(EventHandler.class);
            if (mapperAnnotation != null) {
                EventType[] eventTypes = mapperAnnotation.value();
                for (EventType eventType : eventTypes) {
                    EventDispatcher.getInstance().registerEvent(eventType, handler);
                    map.put(getKey(handler, eventType), method);
                }
            }
        }
    }

    /**
     * 分发给具体监听器执行
     *
     * @param handler
     * @param event
     */
    public void fireEvent(Object handler, BaseGameEvent event) {
        try {
            Method method = map.get(getKey(handler, event.getEventType()));
            ReflectionUtils.makeAccessible(method);
            ReflectionUtils.invokeMethod(method, handler, new Object[]{event});
        } catch (Exception e) {
            log.error("监听器执行异常,handler[{}] event[{}] error{}", new Object[]{handler.getClass().getSimpleName(), event.getEventType(), e});

        }
    }

    private String getKey(Object handler, EventType eventType) {
        return handler.getClass().getName() + "-" + eventType.toString();
    }
}
